package com.maven.demo.service.listener;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.maven.demo.model.pojo.User;

/**
 * @author yanwl
 * @date 2015年9月17日
 */
@Component
@Lazy(value=true)
public class UserListenerRegister implements ApplicationContextAware{
	private static final Logger LOG = Logger.getLogger(UserListenerRegister.class);
	
	private static Set<UserListener> listeners;
	
	/**
	 * 通知相关的监听器
	 * @param oldUser
	 * @param newUser
	 */
	public void adviceUpdate(User oldUser,User newUser) {
		if(listeners == null || listeners.isEmpty()) {
			return;
		}
		for (UserListener listener : listeners) {
			listener.onUpdate(oldUser, newUser);
		}
	}


	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		Map<String,UserListener> map = applicationContext.getBeansOfType(UserListener.class);
		if(listeners == null) {
			listeners = new HashSet<UserListener>();
		}
		listeners.addAll(map.values());
		if(LOG.isInfoEnabled()) {
			LOG.info("加载监听器事件："+listeners);
		}
	}

}
